package main

import (
	"JoDocker/container"
	"encoding/json"
	"fmt"
	"github.com/Sirupsen/logrus"
	"io/ioutil"
	"os"
	"text/tabwriter"
)

// ListContainers docker ps
func ListContainers() {
	dirPath := fmt.Sprintf(container.DefaultInfoLocation, "")
	dirPath = dirPath[:len(dirPath)-1]
	fileSlc, err := ioutil.ReadDir(dirPath)
	if err != nil {
		logrus.Errorf("Read dir %s error %v", dirPath, err)
		return
	}
	var containerSlc []*container.ContainerInfo
	for _, file := range fileSlc {
		containerPtr, err := getContainerInfo(file)
		if err != nil {
			logrus.Errorf("Get container info error %v", err)
			continue
		}
		containerSlc = append(containerSlc, containerPtr)
	}

	w := tabwriter.NewWriter(os.Stdout, 12, 1, 3, ' ', 0)
	fmt.Fprint(w, "ID\tNAME\tPID\tSTATUS\tCOMMAND\tCREATED\n")
	for _, containerPtr := range containerSlc {
		fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n",
			containerPtr.Id,
			containerPtr.Name,
			containerPtr.Pid,
			containerPtr.Status,
			containerPtr.Command,
			containerPtr.CreatedTime,
		)
	}
	if err := w.Flush(); err != nil {
		logrus.Errorf("Flush error %v", err)
		return
	}
}

// 获取容器信息
func getContainerInfo(file os.FileInfo) (*container.ContainerInfo, error) {
	containerName := file.Name()
	configFilePath := fmt.Sprintf(container.DefaultInfoLocation, containerName)
	configFilePath = configFilePath + container.ConfigFileName
	content, err := ioutil.ReadFile(configFilePath)
	if err != nil {
		logrus.Errorf("Read file %s error %v", configFilePath, err)
		return nil, err
	}
	var containerInfo container.ContainerInfo
	if err := json.Unmarshal(content, &containerInfo); err != nil {
		logrus.Errorf("Json unmarshal error %v", err)
		return nil, err
	}
	return &containerInfo, nil
}
